<template>
  <div class="app-container">
    <el-form
      :model="form"
      ref="form"
      label-width="100px"
      v-loading="formLoading"
      :rules="rules"
    >
      <el-form-item label="帖子标题：" prop="title" required>
        <el-input v-model="form.title"></el-input>
      </el-form-item>
      <el-form-item label="帖子内容：" prop="content" required>
        <el-input type="textarea" :rows="10" v-model="form.content"></el-input>
      </el-form-item>

      <el-form-item>
        <el-button type="primary" @click="submitForm">提交</el-button>
        <el-button @click="resetForm">重置</el-button>
      </el-form-item>
    </el-form>
  </div>
</template>

<script>
import forumApi from "@/api/forum";
import { mapActions } from "vuex";

export default {
  data() {
    return {
      form: {
        id: "",
        title: "",
        content: "",
      },
      formLoading: false,
      rules: {
        title: [
          { required: true, message: "请填写帖子标题", trigger: "blur" },
          {
            min: 2,
            max: 100,
            message: "标题长度在 2 到 100 个字符",
            trigger: "blur",
          },
        ],
        content: [
          { required: true, message: "请填写帖子内容", trigger: "blur" },
          {
            min: 5,
            max: 2000,
            message: "内容长度在 5 到 2000 个字符",
            trigger: "blur",
          },
        ],
      },
    };
  },
  methods: {
    submitForm() {
      let _this = this;
      this.$refs.form.validate((valid) => {
        if (valid) {
          this.formLoading = true;
          forumApi
            .createPost(this.form)
            .then((data) => {
              if (data.code === 1) {
                _this.$message.success("发布成功");
                _this.delCurrentView(_this).then(() => {
                  _this.$router.push("/forum/post/list");
                });
              } else {
                _this.$message.error(data.message || "发布失败");
                _this.formLoading = false;
              }
            })
            .catch((e) => {
              _this.formLoading = false;
            });
        }
      });
    },
    resetForm() {
      this.$refs["form"].resetFields();
      this.form = {
        id: "",
        title: "",
        content: "",
      };
    },
    ...mapActions("tagsView", { delCurrentView: "delCurrentView" }),
  },
};
</script>
